package com.mylogistics.service;



import com.mylogistics.mapper.UserMapper;
import com.mylogistics.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 此类用于Security查询账户
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    //查询数据库的用户信息的mapper
    @Autowired
    private UserMapper userMapper;


    @Override
    @Cacheable(value ="cacheTest",key = "#userName")
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = userMapper.getUserByUserName(userName);
        if (user != null) {
            UserDetails userDetails = new UserDetails() {

                //获取当前用户的权限
                @Override
                public Collection<? extends GrantedAuthority> getAuthorities() {
                    List<GrantedAuthority> list = new ArrayList<>();
                    list.add(new SimpleGrantedAuthority("ROLE_"+user.getRole()));
                    return list;
                }

                @Override
                public String getPassword() {
                    return user.getPassword();
                }

                //获取账号
                @Override
                public String getUsername() {
                    return user.getUsername();
                }

                @Override
                public boolean isAccountNonExpired() {
                    return true;
                }

                @Override
                public boolean isAccountNonLocked() {
                    return true;
                }

                @Override
                public boolean isCredentialsNonExpired() {
                    return true;
                }

                @Override
                public boolean isEnabled() {
                    return true;
                }
            };
            return userDetails;
        }
        return null;
    }
}
